import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: const ControlledInteractiveViewer(),
    );
  }
}

class ControlledInteractiveViewer extends StatefulWidget {
  const ControlledInteractiveViewer({super.key});

  @override
  State<ControlledInteractiveViewer> createState() => _ControlledInteractiveViewerState();
}

class _ControlledInteractiveViewerState extends State<ControlledInteractiveViewer> {
  final TransformationController _transformationController = TransformationController();
  final ValueNotifier<bool> _isTransformed = ValueNotifier<bool>(false);

  // 重置变换到初始状态
  void _resetTransformation() {
    _transformationController.value = Matrix4.identity();
    _isTransformed.value = false;
  }

  @override
  void initState() {
    super.initState();
    // 监听变换变化
    _transformationController.addListener(() {
      final matrix = _transformationController.value;
      // 检查是否不是单位矩阵（即有变换）
      _isTransformed.value = matrix != Matrix4.identity();
    });
  }

  @override
  void dispose() {
    _transformationController.dispose();
    _isTransformed.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Controlled Viewer'),
        actions: [
          // 只在有变换时显示重置按钮
          ValueListenableBuilder<bool>(
            valueListenable: _isTransformed,
            builder: (context, isTransformed, child) {
              return isTransformed
                  ? IconButton(
                icon: const Icon(Icons.restore),
                onPressed: _resetTransformation,
              )
                  : const SizedBox.shrink();
            },
          ),
        ],
      ),
      body: Stack(
        children: [
          InteractiveViewer(
            transformationController: _transformationController,
            minScale: 0.1,
            maxScale: 4.0,
            boundaryMargin: const EdgeInsets.all(80),
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [Colors.blue.shade300, Colors.purple.shade300],
                ),
              ),
              child: const Center(
                child: FlutterLogo(size: 200),
              ),
            ),
          ),
          // 显示当前缩放比例
          Positioned(
            bottom: 20,
            right: 20,
            child: ValueListenableBuilder<Matrix4>(
              valueListenable: _transformationController,
              builder: (context, matrix, child) {
                // 从变换矩阵中提取缩放比例（这是一个近似值）
                final scale = matrix.getMaxScaleOnAxis();
                return Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.7),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Text(
                    'Scale: ${scale.toStringAsFixed(2)}x',
                    style: const TextStyle(color: Colors.white),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
